const router = require('koa-router')()
const upload = require('../upload')
const mongoose = require('mongoose')

const Image = mongoose.model('Image')
const Comment = mongoose.model('Comment')
const statsfn = require('../lib/statsfn')

router.prefix('/images')

router.post('/', upload.single('imgfile'), async function(ctx) {
  const {title, description} = ctx.req.body
  const {originalname, mimetype, filename: diskfilename} = ctx.req.file
  const doc = await Image.create({
    title, description, originalname, mimetype, diskfilename
  })
  ctx.redirect(`/images/${doc._id}`)
})

router.get('/:imageid', async ctx => {
  const doc = await Image.findByIdAndUpdate(
    ctx.params.imageid,
    {$inc: {visit: 1}},
    {new: true}
  )
  doc.stats = await statsfn()
  doc.comments = await Comment
    .find({image: ctx.params.imageid})
    .sort({createdAt: -1})
  if(doc) {
    await ctx.render('show', doc)
  }
})

router.post('/likes/:imageid', async ctx => {
  const doc = await Image.findByIdAndUpdate(
    ctx.params.imageid,
    {$inc: {likes: 1}},
    {new: true}
  )
  ctx.body = doc
})
module.exports = router